$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows }) {
    console.log('Data ready event triggered');
    var mstform = $NG.getCmpApi("p_form_equipment_list");
    var dgrid = $NG.getCmpApi('p_form_equipment_list_d');



    $NG.getCmpApi('toolbar_p_form_equipment_list_d').insert({
        id: "user_insert",
        text: "插行",
        iconCls: "icon-InsertRow"
    });
    //按钮事件
    useClick(async function ({ args }) {
        var dgrid = $NG.getCmpApi("p_form_equipment_list_d");
        var orirow = dgrid.getCheckedIndexes()[0] !== undefined
            ? dgrid.getCheckedIndexes()[0]
            : dgrid.getAllData().table.newRow.length;
        var maxrow = dgrid.getAllData().table.newRow.length;
        console.log(orirow);
        dgrid.addRows();
        setTimeout(function () {
            console.log(maxrow);
            dgrid.moveRow(maxrow, orirow + 1);
        }, 100);  // 延迟 100 毫秒，视具体情况可以调整这个值
    }, "user_insert");


    //页面条件
    if (page.oType == "add" || page.oType == "edit" || page.oType == "view" || page.oType == "workflow") {

    }
    $NG.updateUI((updater, state) => {
        updater.editGrid.p_form_equipment_list_d.u_sub_no.setProps({
            cellStyle: { color: "blue", "text-decoration": "underline" },  //设置单元格样式
            headerStyle: { color: "blue", "text-decoration": "underline" },//设置列头样式
        });
    })
    $NG.updateUI((updater, state) => {
        updater.editGrid.p_form_equipment_list_d.u_sub_no.cellStyle({
            cellStyle: { color: "blue", "text-decoration": "underline" },  //设置单元格样式
            // headerStyle: { color: "blue", "text-decoration": "underline" },//设置列头样式
        });
    })
    $NG.updateUI((updater, state) => {

        updater.editGrid.p_form_equipment_list_d.u_sub_no.setProps(p => {
            return { ...p, editor: { ...p.editor, cellStyle: { color: "blue", "text-decoration": "underline" } } };
        });

    })




    $NG.updateUI((updater, state) => {
        updater.fieldSetForm.p_form_equipment_list.u_cnt_no.setProps({
            onBeforeOpen: async () => {
                var phid_pc = $NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue();
                if (!phid_pc) {
                    $NG.alert("请先选择项目");
                    return false;
                } else {
                    return true;
                }
            },
            ...(!!$NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue() && {
                clientSqlFilter: {
                    bill_type: 1,
                    phid_pc: $NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue()
                }
            }),
            onDoubleClick() { // 双击事件
                var u_cnt_phid = $NG.getCmpApi('p_form_equipment_list').getItem('u_cnt_no').getValue();
                if (u_cnt_phid) {
                    // 弹出确认框
                    // var isConfirmed = $NG.confirm("您确定要跳转到合同信息吗？");
                    // if (isConfirmed) {
                    $NG.open(
                        "http://nginx.clouddev.hisense.com" +
                        "/PMS/PCM/CntM/CntMEdit?otype=view&id=" +
                        u_cnt_phid,
                        { AppTitle: "合同信息" }
                    );
                    // }
                }
            },
            onClick() {
                // todo 单击事件
            }
        });
        updater.editGrid.p_form_equipment_list_d.u_u_cnt_list_no.setProps({
            clientSqlFilter: {
                pphid: $NG.getCmpApi('p_form_equipment_list').getItem('u_cnt_no').getValue()
            },
            // cellStyle: { color: "blue", "text-decoration": "underline" },  //设置单元格样式
            // headerStyle: { color: "blue", "text-decoration": "underline" },//设置列头样式
        });
    });


    //选择项目后更新
    useValuesChange(({ args }) => {
        debugger;
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_equipment_list.u_cnt_no.setProps({
                clientSqlFilter: {
                    bill_type: 1,
                    phid_pc: $NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue()
                }
            });
        });

    }, 'p_form_equipment_list.phid_pc');



    //选择合同后更新
    useValuesChange(({ args }) => {
        debugger;
        // 表格通用帮助过滤条件更新
        $NG.updateUI(updater => updater.editGrid.p_form_equipment_list_d.u_u_cnt_list_no.setProps((p) => {
            return {
                ...p, editor: {
                    ...p.editor,
                    clientSqlFilter: { pphid: $NG.getCmpApi('p_form_equipment_list').getItem('u_cnt_no').getValue() },
                }
            };
        }));
        $NG.execServer('getCntInfo', { cnt: mstform.getItem('u_cnt_no').getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas);
            //帮助字段赋值
            $NG.updateState((updater) => {
                //【注意这里的表名不能为控件ID，必须要是表名】
                updater.data.p_form_equipment_list.setProps({
                    u_cnt_name: datas.bill_name,
                    u_product_line: {
                        value: datas.user_product_line,
                        label: datas.user_product_line_name,
                    },
                    u_cnt_type: {
                        value: datas.pct_id,
                        label: datas.pct_name,
                    },
                    u_customer: {
                        value: datas.customer_id,
                        label: datas.customer_name,
                    }
                });
            });

        });

    }, 'p_form_equipment_list.u_cnt_no');


    useUpdateRows(({ args, table }) => {
        const rows = args[0];
        const clearList = {}; // 用于存储清单编号
        let sum_to_u_pur_cost_amt = 0; // 采购成本
        let sum_to_u_svc_cost_amt = 0; // 服务成本
        let sum_to_u_sub_cost = 0; // 拟分包成本
        let clearCodeCounter = 1; // 清单编码计数器，从 1 开始


        rows.forEach((items) => {
            const { u_equipment_list_name, u_model } = items;
            const key = `${u_equipment_list_name}_${u_model}`; // 根据名称和型号生成唯一标识符
            // 如果清单编号不存在，则生成新的编号
            if (!clearList[key]) {
                const serialPart = String(clearCodeCounter).padStart(4, '0'); // 将计数器格式化为4位
                clearList[key] = 'A' + serialPart; // 生成清单编号
                clearCodeCounter++;
            }
            if (!items.u_equipment_list_no) {
                $NG.execServer("getCntDNoByCntId", { cnd_id: mstform.getItem('u_cnt_no').getValue(), item_name: "'" + items.u_equipment_list_name + "'", user_ggxh: "'" + items.u_model + "'" }, function (res) {
                    if (res.count > 0) {
                        var cntdata = JSON.parse(res.data)[0].extendObjects; //单返回值
                        items.u_u_cnt_list_no = cntdata.phid;
                        items.u_u_cnt_list_no_EXName = cntdata.item_no;
                    } else {
                        console.log('没有找到合同清单')
                        items.u_u_cnt_list_no = null;
                        items.u_u_cnt_list_no_EXName = null;
                    }
                    dgrid.refreshView()
                });
            }

            if (items.u_sub_no) {
                $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_sub_no + "'" }, function (res) {
                    if (res.count > 0) {
                        var subdata = JSON.parse(res.data)[0].extendObjects; //单返回值
                        items.u_sub_item = subdata.phid;
                        items.u_sub_item_EXName = subdata.itemname;
                        items.u_sub_ggxh = subdata.spec
                    } else {
                        console.log('没有找到拟分包清单')
                        items.u_sub_item = null;
                        items.u_sub_item_EXName = null;
                        items.u_sub_ggxh = null;
                    }
                });
                items.u_sub_invoice_type = '8570000000000151'
                items.u_sub_invoice_type_EXName = '6%增值税专用发票'
            }
            //如果存在分包项，则分包发票设置为6%，如果存在采购项，采购发票为13%
            if (items.u_u_pur_no) {
                $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_u_pur_no + "'" }, function (res) {
                    if (res.count > 0) {
                        var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值
                        items.u_pur_item = purdata.phid;
                        items.u_pur_item_EXName = purdata.itemname;
                        items.u_pur_ggxh = purdata.spec
                    } else {
                        console.log('没有找到拟采购清单')
                        items.u_u_pur_item = null;
                        items.u_u_pur_item_EXName = null;
                        items.u_pur_ggxh = null;
                    }
                });
                items.u_pur_invoice_type = '8570000000000154'
                items.u_pur_invoice_type_EXName = '13%增值税专用发票'
            }
            //根据名称和型号查询合同信息中的合同清单编码，弹出提示“”
            // 将清单编号赋值到明细对象中的清单编码字段
            items.u_equipment_list_no = clearList[key];
            sum_to_u_pur_cost_amt += parseFloat(items.u_pur_cost_vat) || 0; // 拟采购成本含税
            sum_to_u_svc_cost_amt += parseFloat(items.u_svc_cost) || 0; // 服务成本预计
            sum_to_u_sub_cost += parseFloat(items.u_sub_cost_vat) || 0; // 拟分包成本含税

        });
        // 更新表单状态，将计算出的 sum 赋值给表头字段
        $NG.updateState((updater) => {
            updater.data.p_form_equipment_list.setProps({
                u_pur_cost_amt: sum_to_u_pur_cost_amt,
                u_svc_cost_amt: sum_to_u_svc_cost_amt,
                u_sub_cost: sum_to_u_sub_cost,
            });
        });
        // dgrid.refreshView()
    }, "p_form_equipment_list_d");


    useUpdateRow(({ args, table }) => {
        const record = args[0];
        $NG.execServer("getItemdataByNo", { itemno: "'" + record.u_sub_no + "'" }, function (res) {
            if (res.count > 0) {
                var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                record.u_sub_item = data.phid;
                record.u_sub_item_EXName = data.itemname;
                record.u_sub_ggxh = data.spec
                console.log(record.u_u_sub_item_EXName)
                console.log(data.itemname)
            } else {
                console.log('没有找到拟分包清单')
                record.u_u_sub_item = null;
                record.u_u_sub_item_EXName = null;
                record.u_sub_ggxh = null;
            }
            dgrid.refreshView()
        });
        $NG.execServer("getCntDNoByCntId", { cnd_id: mstform.getItem('u_cnt_no').getValue(), item_name: "'" + record.u_equipment_list_name + "'", user_ggxh: "'" + record.u_model + "'" }, function (res) {
            if (res.count > 0) {
                var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                record.u_u_cnt_list_no = data.phid;
                record.u_u_cnt_list_no_EXName = data.item_no;
                dgrid.refreshView()
            } else {
                // console.log('没有找到合同清单')
                // record.u_u_cnt_list_no = null;
                // record.u_u_cnt_list_no_EXName = null;
                // dgrid.refreshView()
            }
        });
    }, "p_form_equipment_list_d");








    //自动获取设备清单的实施费用和服务费用
    if (page.oType == page.OType.Add || page.oType == page.OType.Edit) {

        console.log(page.oType); //新增 修改 查看 工作流
        var dgrid1 = $NG.getCmpApi('p_form_equipment_list_impl');
        var dgrid2 = $NG.getCmpApi('p_form_equipment_list_svc');


        useValuesChange(({ args }) => {
            console.log(args[0]);
            dgrid1.clearRows();
            dgrid2.clearRows();
            if (dgrid1) {
                $NG.execServer('get_impl_cost_budget_info', {
                    phid_pc: "1"
                }, function (res) {
                    const data = JSON.parse(res.data);
                    console.log(res.data);
                    //默认增行,批量新增表体数据
                    var gridArr = []; //定义表体数组
                    var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                    for (var i = 0; i < gridCount; i++) {
                        var gridObj = {
                        };
                        //对表体字段进行赋值,可以取数据库中的值进行赋值
                        gridObj.u_bill_no = data[i].extendObjects.bill_no;
                        gridObj.u_total_impl_amt = data[i].extendObjects.u_total_impl_labor_amt;
                        gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                        gridObj.u_total_sec_dev_amt = data[i].extendObjects.u_total_sec_dev_amt;
                        gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                        gridArr.push(gridObj);
                    }
                    //调用新增表体行数据的函数

                    dgrid1.addRows(gridArr);
                })
            }
            if (dgrid2) {
                $NG.execServer('get_svc_cost_budget_info', {
                    phid_pc: "1"
                }, function (res) {
                    const data = JSON.parse(res.data);
                    console.log(res.data);
                    //默认增行,批量新增表体数据
                    var gridArr = []; //定义表体数组
                    var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                    for (var i = 0; i < gridCount; i++) {
                        //对表体字段进行赋值,可以取数据库中的值进行赋值
                        var gridObj = {
                        };
                        gridObj.u_bill_no = data[i].extendObjects.bill_no;
                        gridObj.u_total_svc_amt = data[i].extendObjects.u_total_svc_amt;
                        gridObj.u_total_svc_labor_amt = data[i].extendObjects.u_total_svc_labor_amt;
                        gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                        // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                        gridArr.push(gridObj);
                    }
                    //调用新增表体行数据的函数

                    dgrid2.addRows(gridArr);
                })
            }
        }, "p_form_equipment_list.u_product_line");
    }
});